<!-- pages/member/activate-card/index.vue -->
<template>
  <view class="activate-card-page">

    <!-- 卡片预览 -->
    <view class="card-preview">
      <view class="card-container">
        <text class="card-name">{{ cardInfo.title }}</text>
        <text class="card-desc">{{ cardInfo.description }}</text>
        <!-- <text class="card-benefits">特权: {{ cardInfo.benefits }}</text> -->
      </view>
    </view>

    <!-- 开通按钮 -->
    <view class="action-section">
      <button 
        class="activate-btn" 
        :disabled="!canActivate || activating"
        @click="openMemberCard"
      >
        {{ activateText }}
      </button>
      
     <!-- <view class="tips">
        <text class="tip-text">使用微信官方开卡组件，安全便捷</text>
      </view> -->
    </view>

    <!-- 环境检测提示 -->
    <view v-if="!environmentSupported" class="environment-warning">
      <text class="warning-text">当前环境不支持微信开卡功能</text>
      <text class="warning-desc">请使用微信7.0.5以上版本</text>
    </view>

    <!-- 调试信息 -->
    <!-- <view v-if="showDebug" class="debug-section">
      <button @click="checkEnvironment">检查环境</button>
      <button @click="simulateSuccess">模拟成功</button>
    </view> -->
  </view>
</template>

<script>
import WechatBusiness from '@/utils/wechat-business'
import WechatSDK from '@/utils/wx-sdk'
import api from '@/api/wxcard.js';
export default {
  data() {
    return {
      cardId: '',
      cardInfo: {},
      activating: false,
      environmentSupported: true,
      showDebug: process.env.NODE_ENV === 'development',
	  form:{
		  card_id:""
	  },
	  openConfig:{
		  cardId: "",
		  outStr: "", // 商户自定义参数
		  appId: "", // 从配置获取
		  openid: "", // 需要从后端获取或通过授权获取
		  timestamp: "",
		  nonceStr: "",
		  signType: 'SHA1',
		  signature:"" // 需要后端生成
	  }
    }
  },
  
  onLoad(options) {
    this.cardId = options.cardId || 'p6HHw6mj-C_U7pblCqoW0e9L7dSE'
	this.form.card_id = this.cardId;
    this.initPage()
  },
  
  computed: {
    canActivate() {
      //return this.cardId && this.environmentSupported && !this.activating
	  return this.cardId 
    },
    
    activateText() {
      if (this.activating) return '开通中...'
      return '立即开通会员卡'
    }
  },
  
  methods: {
    async initPage() {
      // 检查环境支持
      this.checkEnvironmentSupport()
      
      // 初始化微信 SDK
      await this.initWechatSDK()
      
      // 加载卡片信息
      await this.loadCardInfo()
    },
    
    /**
     * 检查环境支持
     */
    checkEnvironmentSupport() {
      const env = WechatBusiness.checkEnvironment()
      console.log('环境检查:', env)
      
      this.environmentSupported = env.isWechat && env.supportOpenBusinessView
      
      if (!this.environmentSupported) {
        console.warn('环境不支持 openBusinessView:', env)
      }
    },
    
    /**
     * 初始化微信 SDK
     */
    async initWechatSDK() {
      try {
        if (!this.environmentSupported) return
        
        await WechatSDK.init()
        console.log('微信 SDK 初始化成功')
      } catch (error) {
        console.error('微信 SDK 初始化失败:', error)
      }
    },
    
    /**
     * 加载卡片信息
     */
    async loadCardInfo() {
      try {
        // 这里调用后端接口获取卡片信息
        // const response = await this.$api.memberCard.getCardInfo(this.cardId)
		 
		 let clone = this.form;
		 api.getCardInfo(clone).then(res => {
		 	console.log(res,444444);
		 		if(res.code==1){
		 			// this.cardInfo = res.data;
					 //const response = res.data;
					 this.cardInfo = {
					   title: res.data.member_card.base_info.title,
					   description: res.data.member_card.base_info.description,
					   benefits: ''
					 }
		 		}else{
		 			uni.showToast({
		 				title: "卡券信息加载失败",
		 				icon: 'none',
		 				duration: 1000
		 			});
		 		}
		})
    
        
      } catch (error) {
        console.error('加载卡片信息失败:', error)
      }
    },
    
    /**
     * 打开会员卡开卡组件
     */
    async openMemberCard() {
      if (!this.canActivate) return
      
      this.activating = true
      
      try {
        uni.showLoading({
          title: '准备开卡...',
          mask: true
        })
        
        // 1. 获取开卡参数（需要调用后端接口）
        this.getOpenCardConfig();
		
		console.log(this.openConfig,1111)
        
        // 2. 打开开卡组件
        const result = await WechatBusiness.openMemberCard(this.openConfig)
        
        uni.hideLoading()
        
        // 3. 处理开卡结果
        this.handleOpenResult(result)
        
      } catch (error) {
        console.error('打开开卡组件失败:', error)
        uni.hideLoading()
        this.handleOpenError(error)
      } finally {
        this.activating = false
      }
    },
    
    /**
     * 获取开卡配置参数
     */
    async getOpenCardConfig() {
       api.getOpenCardParams({ cardId: this.cardId}).then(res => {
      	
      	let response = res.data  ;
		console.log(response,'getOpenCardConfig');
      	
      	this.openConfig.cardId = response.card_id;
		this.openConfig.outStr = response.out_str;
		this.openConfig.app_id = response.app_id;
		this.openConfig.openid = response.openid;
		this.openConfig.timestamp = response.timestamp;
		this.openConfig.nonceStr = response.nonceStr;
		this.openConfig.signType = response.sign_type;
		this.openConfig.signature = response.signature;
      })
    },
    
    /**
     * 处理开卡结果
     */
    handleOpenResult(result) {
      console.log('开卡结果:', result)
      
      uni.showToast({
        title: '开卡成功！',
        icon: 'success',
        duration: 2000
      })
      
      // 跳转到成功页面或返回
      setTimeout(() => {
        uni.redirectTo({
          url: `/pages/member/activate-card/success?cardId=${this.cardId}`
        })
      }, 1500)
    },
    
    /**
     * 处理开卡错误
     */
    handleOpenError(error) {
      let title = '开卡失败'
      let content = error.message
      
      if (error.message.includes('用户取消')) {
        title = '已取消'
        content = '您取消了开卡操作'
      } else if (error.message.includes('版本过低')) {
        title = '版本过低'
        content = '请升级微信到最新版本'
      }
      
      uni.showModal({
        title: title,
        content: content,
        showCancel: false,
        confirmText: '知道了'
      })
    },
    
    /**
     * 检查环境（调试用）
     */
    checkEnvironment() {
      const env = WechatBusiness.checkEnvironment()
      uni.showModal({
        title: '环境检测',
        content: JSON.stringify(env, null, 2),
        showCancel: false
      })
    },
    
    /**
     * 模拟成功（调试用）
     */
    simulateSuccess() {
      this.handleOpenResult({ success: true })
    }
  }
}
</script>

<style scoped>
.activate-card-page {
  padding: 30rpx;
  min-height: 100vh;
  background: #f5f5f5;
}

.page-header {
  text-align: center;
  margin-bottom: 40rpx;
}

.title {
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
}

.card-preview {
  background: white;
  border-radius: 20rpx;
  padding: 40rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.1);
}

.card-container {
  text-align: center;
}

.card-name {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.card-desc {
  display: block;
  font-size: 28rpx;
  color: #666;
  margin-bottom: 20rpx;
  line-height: 1.5;
}

.card-benefits {
  display: block;
  font-size: 26rpx;
  color: #007AFF;
}

.action-section {
  margin-top: 60rpx;
}

.activate-btn {
  background: linear-gradient(135deg, #007AFF, #5856D6);
  color: white;
  border: none;
  border-radius: 50rpx;
  height: 100rpx;
  line-height: 100rpx;
  font-size: 32rpx;
  font-weight: bold;
  width: 100%;
}

.activate-btn:disabled {
  background: #CCCCCC;
  color: #666666;
}

.tips {
  text-align: center;
  margin-top: 30rpx;
}

.tip-text {
  font-size: 24rpx;
  color: #999;
}

.environment-warning {
  background: #FFF3CD;
  border: 1rpx solid #FFEAA7;
  border-radius: 10rpx;
  padding: 30rpx;
  margin-top: 30rpx;
  text-align: center;
}

.warning-text {
  display: block;
  font-size: 28rpx;
  color: #856404;
  margin-bottom: 10rpx;
}

.warning-desc {
  display: block;
  font-size: 24rpx;
  color: #856404;
}

.debug-section {
  margin-top: 40rpx;
}

.debug-section button {
  background: #6C757D;
  color: white;
  border: none;
  border-radius: 10rpx;
  padding: 20rpx;
  margin: 10rpx 0;
  width: 100%;
}
</style>